﻿using System.Collections.Generic;
using Model;

namespace BusinessObject
{
    public class ProjectUserBO : Repository<ProjectUser>
    {
        #region Singleton

        private static readonly ProjectUserBO _instance = new ProjectUserBO();

        /// <summary>
        /// Instância do objeto singleton.
        /// </summary>
        public static ProjectUserBO Instance
        {
            get { return _instance; }
        }

        private ProjectUserBO() { }

        #endregion Singleton

        public void insertProjectUser(int userID, int projectID, int hours)
        {
            ProjectUser projectUser = new ProjectUser();
            projectUser.UserId = userID;
            projectUser.ProjectId = projectID;
            projectUser.QtdHoras = hours;
            projectUser.User = UserBO.Instance.GetById(userID);
            projectUser.Project = ProjectBO.Instance.GetById(projectID);

            foreach (ProjectUser up in ProjectUserBO.Instance.GetAll())
            {
                if (up.UserId == userID && up.ProjectId == projectID)
                {
                    ProjectUser teste = ProjectUserBO.Instance.GetById(up.Id);
                    teste.QtdHoras = hours;
                    ProjectUserBO.Instance.Update(teste);
                    return;
                }
            }
            ProjectUserBO.Instance.Save(projectUser);
        }

        public IList<Project> getProjectsByUser(int userID)
        {
            IList<Project> projetos = new List<Project>();
            IList<ProjectUser> userProjects = base.GetByCriteria(up => up.UserId == userID);

            foreach (ProjectUser up in userProjects)
            {
                projetos.Add(ProjectBO.Instance.GetProjectByID(up.ProjectId));
            }

            return projetos;
        }

        public IList<ProjectUser> getProjectsUserByUser(int userID)
        {
            return base.GetByCriteria(up => up.UserId == userID);
        }

        public int countTotalEmployees(int id)
        {
            return base.GetByCriteria(up => up.ProjectId == id).Count;
        }

        public int countTotalHours(int id)
        {
            int totalHours = 0;
            IList<ProjectUser> userProjects = base.GetByCriteria(up => up.UserId == id);

            foreach (ProjectUser up in userProjects)
            {
                totalHours += up.QtdHoras;
            }
            return totalHours;
        }
    }
}